<template>
  <div class="private-message-container">
    <div class="header">
      <el-button @click="$router.go(-1)" link icon="ArrowLeft">返回</el-button>
      <h2>私信</h2>
    </div>
    
    <div class="content">
      <div class="user-select">
        <el-input
          v-model="toUser"
          placeholder="输入对方用户名"
          :disabled="toUserLocked"
          @keyup.enter="loadMessages"
        >
          <template #append>
            <el-button @click="loadMessages" :disabled="!toUser">加载消息</el-button>
          </template>
        </el-input>
      </div>

      <div class="message-list" v-if="toUser">
        <div v-for="msg in messages" :key="msg.id" :class="{'my-message': msg.fromUser === user.username, 'other-message': msg.fromUser !== user.username}">
          <div class="message-header">
            <span class="sender">{{ msg.fromUser }}</span>
            <span class="time">{{ formatTime(msg.createdAt) }}</span>
          </div>
          <div class="message-content">{{ msg.content }}</div>
        </div>
      </div>

      <div class="message-input" v-if="toUser">
        <el-input
          v-model="newMessage"
          type="textarea"
          :rows="3"
          placeholder="输入消息内容"
          @keyup.ctrl.enter="sendMessage"
        />
        <el-button type="primary" @click="sendMessage" :disabled="!newMessage.trim()">
          发送 (Ctrl+Enter)
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { messageApi } from '@/utils/api'
import { ElMessage } from 'element-plus'

export default {
  name: 'PrivateMessage',
  setup() {
    const authStore = useAuthStore()
    const user = authStore.user
    const toUser = ref('')
    const toUserLocked = ref(false)
    const newMessage = ref('')
    const messages = ref([])

    const loadMessages = async () => {
      if (!toUser.value) return
      try {
        const res = await messageApi.list(toUser.value)
        messages.value = res.data || []
      } catch (error) {
        ElMessage.error('加载消息失败: ' + (error.response?.data || error.message))
      }
    }

    const sendMessage = async () => {
      if (!toUser.value || !newMessage.value.trim()) return
      try {
        await messageApi.send({ to: toUser.value, content: newMessage.value })
        newMessage.value = ''
        await loadMessages()
        ElMessage.success('发送成功')
      } catch (error) {
        ElMessage.error('发送失败: ' + (error.response?.data || error.message))
      }
    }

    const formatTime = (timeStr) => {
      if (!timeStr) return ''
      try {
        const date = new Date(timeStr)
        return date.toLocaleString('zh-CN', {
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        })
      } catch {
        return ''
      }
    }

    onMounted(() => {
      // 从路由参数获取对方用户名
      const route = useRoute()
      if (route.query.to) {
        toUser.value = route.query.to
        toUserLocked.value = true
        loadMessages()
      }
    })

    return {
      user,
      toUser,
      toUserLocked,
      newMessage,
      messages,
      loadMessages,
      sendMessage,
      formatTime
    }
  }
}
</script>

<style scoped>
.private-message-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  background-color: white;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header h2 {
  margin: 0 0 0 15px;
  color: #333;
}

.content {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.user-select {
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.message-list {
  height: 400px;
  overflow-y: auto;
  padding: 20px;
}

.my-message {
  margin-bottom: 15px;
  text-align: right;
}

.other-message {
  margin-bottom: 15px;
  text-align: left;
}

.message-header {
  margin-bottom: 5px;
  font-size: 12px;
  color: #999;
}

.my-message .message-header {
  text-align: right;
}

.other-message .message-header {
  text-align: left;
}

.sender {
  font-weight: bold;
  color: #409EFF;
}

.time {
  margin-left: 10px;
}

.message-content {
  display: inline-block;
  max-width: 70%;
  padding: 10px 15px;
  border-radius: 15px;
  word-wrap: break-word;
}

.my-message .message-content {
  background-color: #409EFF;
  color: white;
}

.other-message .message-content {
  background-color: #f0f0f0;
  color: #333;
}

.message-input {
  padding: 20px;
  border-top: 1px solid #eee;
  display: flex;
  gap: 10px;
  align-items: flex-end;
}

.message-input .el-textarea {
  flex: 1;
}
</style> 